package com.xbk.seckill.user.application.service.impl;

import com.xbk.seckill.common.cache.distribute.DistributedCacheService;
import com.xbk.seckill.common.constants.SeckillConstants;
import com.xbk.seckill.common.exception.ErrorCode;
import com.xbk.seckill.common.exception.SeckillException;
import com.xbk.seckill.common.shiro.utils.CommonsUtils;
import com.xbk.seckill.common.shiro.utils.JwtUtils;
import com.xbk.seckill.user.application.service.SeckillUserService;
import com.xbk.seckill.user.domain.model.entity.SeckillUser;
import com.xbk.seckill.user.domain.reposity.SeckillUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author xiexu
 * @date 2025/1/11 07:44
 */
@Slf4j
@Service
public class SeckillUserServiceImpl implements SeckillUserService {

    @Autowired
    private SeckillUserRepository seckillUserRepository;

    @Autowired
    private DistributedCacheService distributedCacheService;

    @Override
    public String login(String userName, String password) {
        if (StringUtils.isEmpty(userName)) {
            throw new SeckillException(ErrorCode.USERNAME_IS_NULL);
        }
        if (StringUtils.isEmpty(password)) {
            throw new SeckillException(ErrorCode.PASSWORD_IS_NULL);
        }
        SeckillUser seckillUser = seckillUserRepository.getSeckillUserByUserName(userName);
        if (seckillUser == null) {
            throw new SeckillException(ErrorCode.USERNAME_IS_ERROR);
        }
        String paramsPassword = CommonsUtils.encryptPassword(password, userName);
        if (!paramsPassword.equals(seckillUser.getPassword())) {
            throw new SeckillException(ErrorCode.PASSWORD_IS_ERROR);
        }
        // 生成token
        String token = JwtUtils.sign(seckillUser.getId());
        // 构建redis的缓存key
        String key = SeckillConstants.getKey(SeckillConstants.USER_KEY_PREFIX, String.valueOf(seckillUser.getId()));
        // 缓存到Redis
        distributedCacheService.put(key, seckillUser);
        // 返回Token
        return token;
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public SeckillUser getSeckillUserByUserName(String userName) {
        log.info("seckill-user|获取用户信息|{}", userName);
        SeckillUser seckillUser = seckillUserRepository.getSeckillUserByUserName(userName);
        if (seckillUser != null) {
            seckillUser.setPassword("");
        }
        return seckillUser;
    }

    @Async
    @Override
    public void asyncMethod() {
        log.info("执行了异步任务...");
    }
}
